package com.bobo.auth.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bobo.domain.SysUser;
import com.bobo.service.SysRoleService;
import com.bobo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SysRoleService sysRoleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据前端提供的用户名 去数据查询该用户的信息
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);

        SysUser sysUser = sysUserService.getOne(wrapper);
        if (null == sysUser) {
            throw new UsernameNotFoundException("用户不存在");
        }

        //权限 获取权限信息
        //  List<String> authList = sysRoleService.getAuthByUserId(sysUser.getId());
       List<String> authList = Arrays.asList("ROLE_ADMIN", "ROLE_USER");  //usersService.getAuth(sysUser.getId());//获取登录人的权限
       List<SimpleGrantedAuthority> list = authList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    //    List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER");
        //登录成功把用户的权限，存入redis
     //   redisTemplate.opsForValue().set("AUTH:" + username, list);

        //密码是否正确 交给springSecurity的去校验
        return new User(username, sysUser.getPassword(), list);

    }
}
